<template>
  <div class="sort-container">
    <h1 class="page-title">分类管理</h1>

    <!-- 分类类型选择 -->
    <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
      <el-tab-pane label="公共资源分类" name="public">
        <div>
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddCategory('public')">
              <el-icon><Plus /></el-icon>新增分类
            </el-button>
          </div>

          <el-table :data="publicCategories" border style="width: 100%; margin-top: 20px" v-loading="loading">
            <el-table-column prop="name" label="分类名称" min-width="150" />
            <el-table-column label="图标" width="100">
              <template #default="scope">
                <img v-if="scope.row.icon" :src="scope.row.icon" class="custom-icon" />
                <span v-else>无图标</span>
              </template>
            </el-table-column>
            <el-table-column label="首页图片" width="200">
              <template #default="scope">
                <img v-if="scope.row.homeImage" :src="scope.row.homeImage" class="home-image" />
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="关联点位数量" width="120" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row, 'public')">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row, 'public')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <el-tab-pane label="服务站点分类" name="service">
        <div class="tab-content">
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddCategory('service')">
              <el-icon><Plus /></el-icon>新增分类
            </el-button>
          </div>

          <el-table :data="serviceCategories" border style="width: 100%; margin-top: 20px" v-loading="loading">
            <el-table-column prop="name" label="分类名称" min-width="150" />
            <el-table-column label="图标" width="100">
              <template #default="scope">
                <img v-if="scope.row.icon" :src="scope.row.icon" class="custom-icon" />
                <span v-else>无图标</span>
              </template>
            </el-table-column>
            <el-table-column label="首页图片" width="200">
              <template #default="scope">
                <img v-if="scope.row.homeImage" :src="scope.row.homeImage" class="home-image" />
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="关联点位数量" width="120" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row, 'service')">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row, 'service')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '新增分类'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="formRules" label-position="top">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="图标选择方式">
          <el-radio-group v-model="iconSelectionType">
            <el-radio value="system">系统图标</el-radio>
            <el-radio value="custom">自定义上传</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="iconSelectionType === 'system'" label="选择系统图标" prop="icon">
          <div class="icon-selector">
            <div
              v-for="icon in availableIcons"
              :key="icon"
              class="icon-item"
              :class="{
                selected: categoryForm.icon === icon && iconSelectionType === 'system',
              }"
              @click="selectIcon(icon)"
            >
              <img :src="icon" alt="" />
            </div>
          </div>
        </el-form-item>

        <el-form-item v-if="iconSelectionType === 'custom'" label="上传自定义图标" prop="icon">
          <el-upload
            class="icon-uploader"
            :show-file-list="false"
            action="#"
            :http-request="uploadIcon"
            :before-upload="beforeIconUpload"
            accept=".jpg,.jpeg,.png,.svg,.webp"
          >
            <img
              v-if="categoryForm.icon && iconSelectionType === 'custom'"
              :src="categoryForm.icon"
              class="uploaded-icon"
            />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <div class="upload-tip" v-if="iconSelectionType === 'custom'">
          <el-icon><InfoFilled /></el-icon>
          <span>建议上传尺寸为30px×20px的图标，支持JPG、PNG、SVG格式</span>
        </div>

        <el-form-item label="首页图片上传" prop="homeImage">
          <el-upload
            class="home-image-uploader"
            :show-file-list="false"
            action="#"
            :http-request="uploadHomeImage"
            :before-upload="beforeHomeImageUpload"
            accept=".jpg,.jpeg,.png,.svg,.webp"
          >
            <img v-if="categoryForm.homeImage" :src="categoryForm.homeImage" class="uploaded-home-image" />
            <el-icon v-else class="upload-home-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <div class="upload-tip">
          <el-icon><InfoFilled /></el-icon>
          <span>建议上传首页展示图片，支持JPG、PNG、SVG格式，尺寸建议200px×150px</span>
        </div>

        <el-form-item label="描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" :rows="3" placeholder="请输入分类描述（可选）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm" :loading="loading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { categoryAPI, uploadAPI } from '@/api/index.js'
// 当前活动标签
const activeTab = ref('public')
const availableIcons = [
  '/api/files/briefcase.png',
  '/api/files/conference.png',
  '/api/files/station.png',
  '/api/files/user.png',
]
// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentType = ref('public')
const categoryFormRef = ref(null)
const iconSelectionType = ref('system') // 图标选择方式：system-系统图标，custom-自定义上传
const loading = ref(false) // 加载状态
// 表单数据
const categoryForm = reactive({
  id: null,
  name: '',
  icon: '',
  iconType: 'system', // 图标类型：system-系统图标，custom-自定义上传
  homeImage: '', // 首页图片
  description: '',
  type: '',
})

// 分类数据
const publicCategories = ref([])
const serviceCategories = ref([])
const shareCategories = ref([])

// 获取当前分类数据引用
const getCurrentCategories = () => {
  switch (activeTab.value) {
    case 'public':
      return publicCategories
    case 'service':
      return serviceCategories
    case 'share':
      return shareCategories
    default:
      return publicCategories
  }
}

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}

// 图标上传前检查
const beforeIconUpload = (file) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml', 'image/webp']
  const isAllowedType = allowedTypes.includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isAllowedType) {
    ElMessage.error('图标只能是JPG、PNG、SVG或WEBP格式!')
  }

  if (!isLt2M) {
    ElMessage.error('图标大小不能超过2MB!')
  }

  return isAllowedType && isLt2M
}

// 自定义上传图标处理
const uploadIcon = async (fileInfo) => {
  const file = fileInfo.file
  try {
    loading.value = true
    const response = await uploadAPI.uploadFile(file, 'icon')
    if (response.code === 200) {
      categoryForm.icon = response.data.url
      categoryForm.iconType = 'custom'
      ElMessage.success('图标上传成功')
    } else {
      ElMessage.error(response.message || '图标上传失败')
    }
  } catch (error) {
    console.error('图标上传错误:', error)
    ElMessage.error('图标上传失败')
  } finally {
    loading.value = false
  }
}

// 首页图片上传前检查
const beforeHomeImageUpload = (file) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg+xml', 'image/webp']
  const isAllowedType = allowedTypes.includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isAllowedType) {
    ElMessage.error('首页图片只能是JPG、PNG、SVG或WEBP格式!')
  }

  if (!isLt5M) {
    ElMessage.error('首页图片大小不能超过5MB!')
  }

  return isAllowedType && isLt5M
}

// 上传首页图片处理
const uploadHomeImage = async (fileInfo) => {
  const file = fileInfo.file
  try {
    loading.value = true
    const response = await uploadAPI.uploadFile(file, 'home-image')
    if (response.code === 200) {
      categoryForm.homeImage = response.data.url
      ElMessage.success('首页图片上传成功')
    } else {
      ElMessage.error(response.message || '首页图片上传失败')
    }
  } catch (error) {
    console.error('首页图片上传错误:', error)
    ElMessage.error('首页图片上传失败')
  } finally {
    loading.value = false
  }
}

// 加载分类数据
const loadCategories = async (type) => {
  try {
    loading.value = true
    const response = await categoryAPI.getList(type)
    if (response.code === 200) {
      const categories = getCurrentCategories()
      categories.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载分类数据失败')
    }
  } catch (error) {
    console.error('加载分类数据错误:', error)
    ElMessage.error('加载分类数据失败')
  } finally {
    loading.value = false
  }
}

// 监听图标选择类型变化
watch(iconSelectionType, (newVal) => {
  if (newVal === 'system') {
    categoryForm.iconType = 'system'
    if (categoryForm.iconType !== 'system') {
      categoryForm.icon = ''
    }
  } else {
    categoryForm.iconType = 'custom'
    if (categoryForm.iconType !== 'custom') {
      categoryForm.icon = ''
    }
  }
})

// 处理标签切换
const handleTabClick = (tab) => {
  activeTab.value = tab.props.name
  loadCategories(tab.props.name)
}

// 添加分类
const handleAddCategory = (type) => {
  isEdit.value = false
  currentType.value = type
  resetForm(type)
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row, type) => {
  isEdit.value = true
  currentType.value = type
  Object.assign(categoryForm, row)

  // 设置图标选择类型
  iconSelectionType.value = row.iconType || 'system'

  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (row, type) => {
  ElMessageBox.confirm(`确定删除【${row.name}】分类吗？删除后将会清空该分类下的【所有点位数据】。`, '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        loading.value = true
        const response = await categoryAPI.delete(row.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          // 重新加载当前类型的分类数据
          await loadCategories(type)
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除分类错误:', error)
        ElMessage.error('删除失败')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {})
}

// 选择图标
const selectIcon = (icon) => {
  categoryForm.icon = icon
  categoryForm.iconType = 'system'
}

// 提交表单
const handleSubmitForm = async () => {
  if (!categoryFormRef.value) return

  // 检查图标是否已选择
  if (!categoryForm.icon) {
    ElMessage.error('请选择或上传图标')
    return
  }

  categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        categoryForm.type = currentType.value

        let response
        if (isEdit.value) {
          // 编辑现有分类
          response = await categoryAPI.update(categoryForm.id, categoryForm)
          if (response.code === 200) {
            ElMessage.success('更新成功')
          } else {
            ElMessage.error(response.message || '更新失败')
            return
          }
        } else {
          // 新增分类
          response = await categoryAPI.create(categoryForm)
          if (response.code === 200) {
            ElMessage.success('添加成功')
          } else {
            ElMessage.error(response.message || '添加失败')
            return
          }
        }

        dialogVisible.value = false
        // 重新加载当前类型的分类数据
        await loadCategories(currentType.value)
      } catch (error) {
        console.error('提交表单错误:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = (type) => {
  categoryForm.id = null
  categoryForm.name = ''
  categoryForm.icon = ''
  categoryForm.iconType = 'system'
  categoryForm.homeImage = ''
  categoryForm.description = ''
  categoryForm.type = type
}

onMounted(() => {
  // 初始化加载默认分类数据
  loadCategories(activeTab.value)
})
</script>

<style scoped>
.sort-container {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.operation-bar {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

/* 图标选择器样式 */
.icon-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  max-height: 200px;
  overflow-y: auto;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

.icon-item {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  background-color: #f0f2f5;
}

.icon-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

/* 自定义图标上传样式 */
.icon-uploader {
  display: flex;
  justify-content: center;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.upload-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

.uploaded-icon {
  width: 60px;
  height: 60px;
  object-fit: contain;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.upload-tip .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.custom-icon {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.home-image {
  width: 160px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

/* 首页图片上传样式 */
.home-image-uploader {
  display: flex;
  justify-content: center;
}

.upload-home-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.upload-home-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

.uploaded-home-image {
  width: 160px;
  height: 60px;
  object-fit: cover;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}
</style>
